package cn.tedu.mall.seckill.service.Impl;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.front.service.IFrontSpuDetailService;
import cn.tedu.mall.pojo.product.vo.SpuDetailStandardVO;
import cn.tedu.mall.pojo.seckill.vo.SeckillSpuDetailSimpleVO;
import cn.tedu.mall.pojo.seckill.vo.SeckillSpuVO;
import cn.tedu.mall.seckill.service.ISeckillSpuService;
import cn.tedu.mall.seckill.utils.BloomFilter;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;


/**
 * @author zhangyiping
 * @date 2024/1/19
 */
@Service
public class SeckillSpuServiceImpl implements ISeckillSpuService {
    public static final String SECKILL_SPUS_KEY = "seckill:spus";
    public static final String SECKILL_SPU_PREFIX = "seckill:spu:";

    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private IFrontSpuDetailService frontSpuDetailService;

    @Override
    public JsonPage<SeckillSpuVO> listSeckillSpus(Integer page, Integer pageSize) {
        // 所有数据查询 在秒杀都走缓存
        List<SeckillSpuVO> spuList = (List<SeckillSpuVO>) redisTemplate.opsForValue().get(SECKILL_SPUS_KEY);
        // 判断下缓存有没有数据
        if (spuList == null || spuList.isEmpty()) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "当前缓存没有数据，请检查预热逻辑");
        }
        return JsonPage.defaultPage(spuList);
    }

    @Autowired
    private BloomFilter bloomFilter;
    @Override
    public SeckillSpuVO getSeckillSpu(Long spuId) {
//        bloomFilter.spuExist(spuId);
        SeckillSpuVO seckillSpuVO = (SeckillSpuVO) redisTemplate.opsForValue().get(SECKILL_SPU_PREFIX + spuId);
        if (seckillSpuVO == null) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "没有此ID对应的Spu，请检查预热逻辑");
        }
        // 判断当前系统时间是否在秒杀时间段内，若不在，则不返回由随机字符串拼接成的url参数
        LocalDateTime now = LocalDateTime.now();
        Duration afterStart = Duration.between(seckillSpuVO.getStartTime(), now);
        Duration beforeEnd = Duration.between(now, seckillSpuVO.getEndTime());
        if (afterStart.isNegative() || beforeEnd.isNegative()) {
            seckillSpuVO.setUrl(null);
        }
        return seckillSpuVO;
    }

    @Override
    public SeckillSpuDetailSimpleVO getSeckillSpuDetail(Long spuId) {
        SpuDetailStandardVO spuDetailStandardVO = frontSpuDetailService.getSpuDetail(spuId);
        SeckillSpuDetailSimpleVO spuDetail = new SeckillSpuDetailSimpleVO();
        BeanUtils.copyProperties(spuDetailStandardVO, spuDetail);
        return spuDetail;
    }
}
